module WF {
	export class SingleButton extends eui.Component
	{
		public m_normalFile: any = "";

		public m_imgNormal: eui.Image;

		private m_callFunc:Function;

		private m_pressState:boolean;
		private m_pressScale:number = 0.97;

		public constructor(_normalFile: any) {
			super();
			this.m_normalFile = _normalFile;
		}

		public set pressScale(_pressScale:number)
		{
			this.m_pressScale = _pressScale;
		}

		public get normalFile(): any {
			return this.m_normalFile;
		}

		public set normalFile(_normalFile: any) {
			if (_normalFile == null) return;
			if (_normalFile == this.m_normalFile) return;
			this.m_normalFile = _normalFile;
			if (this.m_imgNormal) {
				this.m_imgNormal.source = _normalFile;
			}
			this.updateSize();
		}

		//设置锚点居中，并处理因锚点改变位置错乱问题
		private updateSize(): void 
		{
			if (this.m_imgNormal)
			{
				this.width = this.m_imgNormal.width;
				this.height = this.m_imgNormal.height;

				this.x += (this.width * 0.5 - this.anchorOffsetX) * this.scaleX;
				this.y += (this.height * 0.5 - this.anchorOffsetY) * this.scaleY;

				this.anchorOffsetX = this.width * 0.5;
				this.anchorOffsetY = this.height * 0.5;
			}
		}

		public set callFunc(_callFunc:Function)
		{
			this.m_callFunc = _callFunc;
		}

		protected partAdded(_partName: string, _instance: any): void
		{
			super.partAdded(_partName, _instance);
			if (_instance == this.m_imgNormal) {
				this.m_imgNormal.source = this.m_normalFile;
			}
		}

		protected childrenCreated(): void 
		{
			super.childrenCreated();
			
			this.updateSize();

			this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.onTouchBegin, this);
			this.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchEnd, this);
			this.addEventListener(egret.TouchEvent.TOUCH_END, this.onTouchCancel, this);
			this.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.onTouchCancel, this);
		}

		public onTouchBegin(_event: egret.TouchEvent): void 
		{
			if(this.m_pressState)return;
			this.m_pressState = true;

			this.scaleX *= this.m_pressScale;
			this.scaleY *= this.m_pressScale;
		}

		public onTouchEnd(_event: egret.TouchEvent): void 
		{
			if(!this.m_pressState)return;
			this.m_pressState = false;

			this.scaleX *= (1.0 / this.m_pressScale);
			this.scaleY *= (1.0 / this.m_pressScale);

			if(this.m_callFunc)
			{
				this.m_callFunc(this);
			}
		}

		public onTouchCancel(_event: egret.TouchEvent): void
		{
			if(!this.m_pressState)return;
			this.m_pressState = false;

			this.scaleX *= (1 / this.m_pressScale);
			this.scaleY *= (1 / this.m_pressScale);
		}
	}
}